﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace Department.admin.SiteStructure
{
    public partial class EditPages : System.Web.UI.Page
    {
        private string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                Response.Redirect("/admin/Login.aspx");
            }

            if (Request.Params["ID"] == null) // Redirect user if the page is loaded without params
            {
                Response.Redirect("/admin/SiteStructure/ViewAllPages.aspx");
            }

            this.Page.Title = "Редакция на новина";
            AdminVariablesSingleton.configureCKEditor(ref CKEditor);

            string heading;
            string text;
            int typeValue = 0;
            int menuValue;
            bool isHidden;
            string id = Request.Params["ID"];
            if (!Page.IsPostBack)
            {
                if (!(id == null))
                {
                    SqlConnection conn = new SqlConnection(strConnString);

                    try
                    {
                        conn.Open();

                        //Gets the news heading
                        string sqlHeading = "SELECT Name From Pages WHERE ID = @ID";
                        SqlCommand comHeading = new SqlCommand(sqlHeading, conn);
                        comHeading.Parameters.AddWithValue("@ID", id);
                        heading = Convert.ToString(comHeading.ExecuteScalar());
                        headingTextBox.Text = heading;

                        string sqlType = "SELECT Pages.TypeID FROM Type INNER JOIN Pages ON Type.ID = Pages.TypeID WHERE (Pages.ID = @ID)";
                        SqlCommand comType = new SqlCommand(sqlType, conn);
                        comType.Parameters.AddWithValue("@ID", id);
                        typeValue = Convert.ToInt32(comType.ExecuteScalar());
                        if (typeValue != 0)
                        {
                            DropDownListDynamicContent.SelectedValue = Convert.ToString(typeValue);
                        }
                        else
                        {
                            DropDownListDynamicContent.SelectedIndex = 0;
                        }

                        string sqlMenu = "SELECT Pages.MenuID FROM Menu INNER JOIN Pages ON Menu.ID = Pages.MenuID WHERE (Pages.ID = @ID)";
                        SqlCommand comMenu = new SqlCommand(sqlMenu, conn);
                        comMenu.Parameters.AddWithValue("@ID", id);
                        menuValue = Convert.ToInt32(comMenu.ExecuteScalar());
                        if (menuValue != 0)
                        {                            
                            DropDownListMenu.SelectedValue = Convert.ToString(menuValue);
                        }
                        else
                        {
                            DropDownListMenu.Items.Add(new ListItem("--"));
                            DropDownListMenu.SelectedIndex = 0;
                        }

                        //Gets the news text
                        string sqlText = "SELECT SiteContent From Pages WHERE ID = @ID";
                        SqlCommand comText = new SqlCommand(sqlText, conn);
                        comText.Parameters.AddWithValue("@ID", id);
                        text = Convert.ToString(comText.ExecuteScalar());
                        CKEditor.Text = text;

                        //Checks if the news is hidden or not
                        string sqlIsHidden = "SELECT IsMain FROM Pages WHERE ID = @ID";
                        SqlCommand comIsHidden = new SqlCommand(sqlIsHidden, conn);
                        comIsHidden.Parameters.AddWithValue("@ID", id);
                        isHidden = Convert.ToBoolean(comIsHidden.ExecuteScalar());
                        checkboxActive.Checked = isHidden;

                        string sqlIsChecked = "SELECT DISTINCT RoleName, RoleId FROM dbo.v_PageRights";
                        SqlCommand comIsChecked = new SqlCommand(sqlIsChecked, conn);
                        SqlDataReader reader = comIsChecked.ExecuteReader();

                        int index = 0;
                        
                        while (reader.Read())
                        {
                            if (rolesGridView.Rows[index].Cells[1].Text.Equals(reader.GetGuid(1)))
                            {
                                ((CheckBox)rolesGridView.Rows[index].Cells[2].Controls[0]).Checked = true;
                                index++;
                            }
                        }  
                    }

                    catch (SqlException sqle)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
                    }
                    catch (Exception ex)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }

        protected void buttonSubmit_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlUpdate = "UPDATE Pages SET Name=@Heading, SiteContent=@Text, IsMain=@IsMain, TypeID=@TypeID, MenuID=@MenuID WHERE ID = @ID";
                SqlCommand comUpdate = new SqlCommand(sqlUpdate, conn);
                string meca = headingTextBox.Text;
                comUpdate.Parameters.AddWithValue("@ID", Request.Params["ID"]);
                comUpdate.Parameters.AddWithValue("@Heading", headingTextBox.Text);
                comUpdate.Parameters.AddWithValue("@Text", CKEditor.Text);
                if (DropDownListDynamicContent.SelectedValue != "--")
                {
                    comUpdate.Parameters.AddWithValue("@TypeID", DropDownListDynamicContent.SelectedValue);
                }
                else
                {
                    comUpdate.Parameters.AddWithValue("@TypeID", Convert.DBNull);
                }
                if (DropDownListMenu.SelectedValue != "--")
                {
                    comUpdate.Parameters.AddWithValue("@MenuID", DropDownListMenu.SelectedValue);
                }
                else
                {
                    comUpdate.Parameters.AddWithValue("@MenuID", Convert.DBNull);
                }
                
                comUpdate.Parameters.AddWithValue("@IsMain", checkboxActive.Checked);


                comUpdate.ExecuteNonQuery();
                Response.Redirect("~/admin/SiteStructure/ViewAllPages.aspx");
            }
            catch (SqlException sqlEx)
            {
                sqlEx.ToString();
                ErrorLabel.Visible = true;
                ErrorLabel.Text = "Възникна грешка проверете отново. Може да има само една страница към меню.";
            }
            finally
            {
                conn.Close();
            }
        }

    }
}